/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, remove the copyright
 * infomation is regarded invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.action;

import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.hibernate.Transaction;

import com.mr.qa.UserSession;
import com.mr.qa.UserSessionUtil;
import com.mr.qa.bo.Comment;
import com.mr.qa.bo.Question;
import com.mr.qa.bo.QuestionCategory;
import com.mr.qa.bo.QuestionComment;
import com.mr.qa.bo.SharedFile;
import com.mr.qa.bo.SharedFileComment;
import com.mr.qa.bo.User;
import com.mr.qa.dao.impl.CommentDAO;
import com.mr.qa.dao.impl.QuestionDAO;
import com.mr.qa.dao.impl.SharedFileDAO;
import com.mr.qa.dao.impl.UserDAO;
import com.mr.qa.exception.QaException;
import com.mr.qa.form.CommentForm;
import com.mr.qa.util.HibernateSessionFactory;

public class CommentAction extends BaseAction {
	private static final Log log = LogFactory.getLog(CommentAction.class);

	public ActionForward doAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ActionForward af = null;
		UserSession us = UserSessionUtil.getUserSession(request);
		String action = this.getAction(request);
		CommentForm commentForm = (CommentForm) form;
		ActionMessages errors = new ActionMessages();
		ActionMessages messages = new ActionMessages();
		if (us == null) {
			errors.add("relogin", new ActionMessage("login.required"));
			action = "login";
		} else {
			if ("add".equals(action)) {
				String content = commentForm.getContent();
				String subjectType = commentForm.getSubjectType();
				String subjectId = commentForm.getSubjectId();
				Date date = new Date();
				if ("Q".equals(subjectType)) {
					if(us.isActive()){
						addForQuestion(content, date, new Integer(subjectId), us.getUserId());
					}
					action = "addforq";
				} else if ("L".equals(subjectType)) {
					subjectType = "Q";
					action = "addforl";
					if(us.isActive()){
						addForQuestion(content, date, new Integer(subjectId), us.getUserId());
					}
				} else if ("T".equals(subjectType)) {
					subjectType = "Q";
					action = "addfort";
					if(us.isActive()){
						addForQuestion(content, date, new Integer(subjectId), us.getUserId());
					}
				} else if ("S".equals(subjectType)) {
					action = "addfors";
					if(us.isActive()){
						addForSharedFile(content, date, new Integer(subjectId), us.getUserId());
					}
				}
				if(!us.isActive()){
					errors.add("addquestion-limit", new ActionMessage("user.inactive", ""));
				}
				String path = mapping.findForward(action).getPath();
				path = path.replace("!?", subjectId);
				af = new ActionForward(path);
				af.setRedirect(true);
			} else if ("delete".equals(action)) {
				HashMap map = delete(new Integer(commentForm.getId()), us
						.getType());
				Integer subjectId = (Integer) map.get("subjectId");
				String subjectType = (String) map.get("subjectType");
				if ("Q".equals(subjectType)) {
					action = "deleteforq";
				} else if ("L".equals(subjectType)) {
					action = "deleteforl";
				} else if ("T".equals(subjectType)) {
					action = "deletefort";
				} else if ("S".equals(subjectType)) {
					action = "deletefors";
				}
				String path = mapping.findForward(action).getPath();
				path = path.replace("!?", subjectId + "");
				af = new ActionForward(path);
				af.setRedirect(true);
			} else if ("list".equals(action)) {
			}
		}
		if (errors.size() > 0)
			saveErrors(request, errors);
		if (messages.size() > 0)
			saveMessages(request, messages);
		if (af == null)
			return mapping.findForward(action);
		else
			return af;
	}

	private void addForSharedFile(String conent, Date date, Integer qid,
			Integer userId) throws QaException {
		Transaction tx = null;
		try {
			CommentDAO commentDAO = new CommentDAO();
			UserDAO userDAO = new UserDAO();
			SharedFileDAO sfDAO = new SharedFileDAO();
			tx = HibernateSessionFactory.getSession().beginTransaction();
			User user = userDAO.findById(userId);
			SharedFile sf = sfDAO.findById(qid);
			SharedFileComment sfComment = new SharedFileComment();
			sfComment.setContent(conent);
			sfComment.setPostDate(date);
			// question.setPostDate(date);
			sf.setChangeDate(date);
			sfComment.setMrIaskUser(user);
			sfComment.setSharedFile(sf);
			commentDAO.saveSharedFileComment(sfComment);
			sfDAO.modify(sf);
			tx.commit();
		} catch (Exception re) {
			if (tx != null)
				tx.rollback();
			throw new QaException(re);
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	private void addForQuestion(String conent, Date date, Integer qid,
			Integer userId) throws QaException {
		Transaction tx = null;
		try {
			CommentDAO commentDAO = new CommentDAO();
			UserDAO userDAO = new UserDAO();
			QuestionDAO questionDAO = new QuestionDAO();
			tx = HibernateSessionFactory.getSession().beginTransaction();
			User user = userDAO.findById(userId);
			Question question = questionDAO.findById(qid);
			QuestionComment comment = new QuestionComment();
			comment.setContent(conent);
			comment.setPostDate(date);
			// question.setPostDate(date);
			// question.setChangeDate(date);
			comment.setMrIaskUser(user);
			comment.setMrIaskQuestion(question);
			commentDAO.save(comment);
			questionDAO.update(question);
			tx.commit();
		} catch (Exception re) {
			if (tx != null)
				tx.rollback();
			throw new QaException(re);
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	public HashMap delete(Integer commentId, String userType)
			throws QaException {
		Transaction tx = null;
		Integer subjectId = 0;
		String subjectType = "N";
		try {
			CommentDAO commentDAO = new CommentDAO();
			tx = HibernateSessionFactory.getSession().beginTransaction();
			Comment comment = commentDAO.findById(commentId);
			if (comment instanceof QuestionComment) {
				Question question = ((QuestionComment) comment)
						.getMrIaskQuestion();
				subjectId = question.getId();
				QuestionDAO questionDao = new QuestionDAO();
				QuestionCategory category = question.getMrIaskCategory();
				if (category.getType() == 0) {
					subjectType = "Q";
				} else if (category.getType() == 1) {
					subjectType = "L";
				} else if (category.getType() == 2) {
					subjectType = "T";
				}
			}
			if (comment instanceof SharedFileComment) {
				subjectId = ((SharedFileComment) comment).getSharedFile()
						.getId();
				subjectType = "S";
			}
			commentDAO.delete(comment);
			tx.commit();
		} catch (Exception re) {
			if (tx != null)
				tx.rollback();
			// throw new QaException(re);
		} finally {
			HibernateSessionFactory.closeSession();
		}
		HashMap map = new HashMap(2);
		map.put("subjectId", subjectId);
		map.put("subjectType", subjectType);
		return map;
	}
}
